import React, { useState, useEffect, useRef } from 'react'
import { Input, Button } from 'antd';
import { SearchOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { useSpring, animated } from 'react-spring'
import pubsub from 'pubsub-js'
import { useNavigate } from 'react-router-dom'
import { textTranslate } from '../../api/translate'
import { uuidFormat } from '../../utility/uuidFormat'
import { SHA256 } from '../../utility/crypto'
import "./index.scss"
const { TextArea } = Input;

export default function Main() {
  const [val, setVal] = useState("")
  const [audioSrc, setAudioSrc] = useState("")
  const [textFlipFlag, setTextFlipFlag] = useState(false)
  const [resVal, setResVal] = useState({})
  const targetTranslate = useRef({})

  useEffect(() => {
    pubsub.subscribe('getFormToVal', (funcName, res) => {
      targetTranslate.current = res
    })
  })

  async function userClickTranslate() {
    if (textFlipFlag) return;
    const { current = {} } = targetTranslate
    let from = current.switchFlag ? "auto" : current.formVal
    const q = val
    const to = current.toVal
    const appKey = "237af33554b809a3"
    const salt = uuidFormat()
    const signInputVal = signInput(q)
    const curtime = Math.round(new Date().getTime() / 1000)
    const key = "I2jgBPowOemOyVbXGiFoO42OCR6Mflup"
    const sign = SHA256(`${appKey}${signInputVal}${salt}${curtime}${key}`).toLocaleUpperCase()
    const signType = "v3"
    const voice = 0
    const strict = true

    const textTranslateVal = await textTranslate({
      q, from, to, appKey, salt, sign, signType, curtime, voice, strict
    })

    const { translation = [], tSpeakUrl = "" } = textTranslateVal
    setResVal(translation[0])
    setAudioSrc(tSpeakUrl)
  }

  // function userClickTranslateBaidu() {
  //   // const { current = {} } = targetTranslate
  //   // let from = current.switchFlag ? "auto" : current.formVal
  //   // const q = val
  //   // const to = current.toVal;
  //   // const appid = "20220605001238843";
  //   // const salt = new Date().getTime();
  //   // const key = "wSJ8K5mwWQUbAh0fh22y";
  //   // const sign = MD5(`${appid}${q}${salt}${key}`);

  //   // jsonp(`http://api.fanyi.baidu.com/api/trans/vip/translate?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`, {}, function (err, res) {
  //   //   const { dst = "" } = res.trans_result && res.trans_result[0]
  //   //   setResVal(dst)
  //   // })
  // }
  function signInput(q) {
    // 其中，input的计算方式为：
    // input=q前10个字符 + q长度 + q后10个字符（当q长度大于20）或 
    // input=q字符串（当q长度小于等于20）；
    const len = q.length;
    if (len <= 20) return q;
    return q.substring(0, 10) + len + q.substring(len - 10, len);
  }

  const styles = useSpring({
    from: { opacity: 1 },
    to: {
      opacity: textFlipFlag ? 0 : 1,
      rotateX: `${textFlipFlag ? 180 : 0}deg`
    },
    delay: 250,
  })

  const showStyles = useSpring({
    from: { opacity: 0 },
    to: {
      opacity: textFlipFlag ? 1 : 0,
      rotateX: `${textFlipFlag ? 360 : 0}deg`
    }
  })

  function editTextFlipFlag() {
    setTextFlipFlag(!textFlipFlag)
    userClickTranslate()
  }

  const onChange = ({ currentTarget }) => {
    setVal(currentTarget.value)
  }

  return (
    <div className='main'>
      <animated.div className={`textArea ${textFlipFlag ? "show" : ""}`} style={styles}>
        <TextArea
          className='textArea_textArea'
          placeholder="输入或粘贴文本进行翻译"
          allowClear onChange={onChange}
        />
      </animated.div>

      <animated.div className={`textArea ${textFlipFlag ? "" : "show"}`} style={showStyles}>
        <TextArea style={{ fontWeight: 900, fontSize: "24px" }} value={resVal} disabled={true} className='textArea_textArea' />
      </animated.div>

      {
        val ? <ChainExample audioSrc={audioSrc} text={textFlipFlag} onClick={editTextFlipFlag} /> : null
      }
    </div>
  )
}

function ChainExample(props) {
  const navigate = useNavigate()
  const styles = useSpring({
    from: { opacity: 0 },
    to: { opacity: 1 },
    delay: 250,
  })

  function handleClick() {
    props.onClick()
  }

  function manyHandleClick() {
    navigate("/many-translate")
  }

  return (
    <animated.div
      style={styles}>
      <Button
        className='main_search_btn'
        type="primary"
        icon={<MenuUnfoldOutlined />}
        onClick={manyHandleClick}
      >
        多种翻译
      </Button>

      <Button
        className='main_search_btn'
        type="primary"
        icon={props.text ? null : <SearchOutlined />}
        onClick={handleClick}
      >
        {props.text ? "重置" : "翻译"}
      </Button>

      <audio
        src={props.audioSrc} controls="controls">
        Your browser does not support the audio element.
      </audio>
    </animated.div>


  )
}
